package com.atyjh.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.dto.UserDTO;
import com.atyjh.reggie.entity.AddressBook;
import com.atyjh.reggie.entity.User;
import com.atyjh.reggie.service.IUserService;
import com.atyjh.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

import static com.atyjh.reggie.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.21
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public Result<UserDTO> login(@RequestBody Map<String, String> map, HttpSession session) {

//        1. 获取手机号和验证码
        String phone = map.get("phone");
        String code = map.get("code");
//        2. 获取session中的验证码
        Object readCode = session.getAttribute(phone);
        if (readCode == null || !readCode.equals(code)) {
            return Result.error("验证码无效！");
        }
//        3. 判断该手机号是否注册过
        LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(User::getPhone, phone);
        User user = userService.getOne(ulqw);
        if (user == null) {
//            3.1 没注册过，注册一下（我最讨厌自动注册的软件了(•́へ•́╬)）
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
//        注没注册都来保存一下
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user, userDTO);
        session.setAttribute(LOGIN_USER_KEY, userDTO);
        return Result.success(userDTO);

    }
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StrUtil.isEmpty(phone)) {
            return Result.error("手机号不能为空");
        }
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        session.setAttribute(phone, code);
        log.info(code);
        return Result.success("验证码来咯！！");
    }


}









